import request from "@/utils/request";

function handleResponse(response) {
  if (response?.data?.error) {
    console.error("RTSP API Error:", response.data.error);
    throw new Error(response.data.error.message || "RTSP API 请求失败");
  }
  if ("result" in response?.data) {
    return response.data.result;
  }
  console.error("Unexpected RTSP API response format:", response?.data);
  throw new Error("RTSP API 响应格式错误或非预期结果");
}

export async function getRTSPConfig() {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      id: `rtsp-get-config-${Date.now()}`,
      method: "rtsp.getConfig",
      params: {}
    });
    return handleResponse(response);
  } catch (error) {
    console.error("获取RTSP配置失败:", error);
    throw error instanceof Error ? error : new Error("获取RTSP配置失败");
  }
}

export async function setRTSPConfig(config) {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      id: `rtsp-set-config-${Date.now()}`,
      method: "rtsp.setConfig",
      params: config
    });
    return handleResponse(response);
  } catch (error) {
    console.error("设置RTSP配置失败:", error);
    throw error instanceof Error ? error : new Error("设置RTSP配置失败");
  }
}

export function validateRtspPort(port) {
  const portNumber = Number(port);
  return Number.isInteger(portNumber) && portNumber >= 1 && portNumber <= 65535;
}
